package com.molichuxing.services.business;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.services.business.dto.request.create.MotRequestCreateDto;
import com.molichuxing.services.business.dto.response.ThirdMotDto;
import com.molichuxing.services.business.dto.response.ThirdMotStateDto;
import com.molichuxing.services.business.service.MotBizService;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dto.request.create.ThirdMotCreateDto;
import com.molichuxing.services.infrastructure.dto.request.create.ThirdMotStateCreateDto;
import com.molichuxing.services.infrastructure.service.MotLogService;
import com.molichuxing.services.infrastructure.service.MotLogStateService;
import com.molichuxing.services.infrastructure.service.impl.NotifyPushServiceImpl;
import com.molichuxing.services.util.JsonUtils;
import com.molichuxing.services.util.MotUtils;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("motBizService")
public class MotBizServiceImpl implements MotBizService {

    private static final Logger logger = LoggerFactory.getLogger(MotBizServiceImpl.class);

    @Resource
    MotUtils motUtils;

    @Resource
    MotLogService motLogService;

    @Resource
    MotLogStateService motLogStateService;

    @Value("${mot.group.id}")
    private String strKey;

    @Value("${mot.group.name}")
    private String groupName;

    @Value("${mot.add.url}")
    private String addUrl;

    @Value("${mot.query.url}")
    private String queryUrl;


    private final static String PARAM_KEY = "strKey"; //（密钥）
    private final static String PARAM_NAME = "strName";//（车主姓名）
    private final static String PARAM_PHONE = "strPhone";//电话号码
    private final static String PARAM_LICENSE = "strCarNumber";// 车牌号
    private final static String PARAM_VIN = "strVIN";// 车架号
    private final static String PARAM_ADDRESS = "AcceptAddress";// 合格证邮寄地址
    private final static String PARAM_INSURANCE = "InsuranceZM";// 有效期内交强险保单副本照片
    private final static String PARAM_GROUP_ID = "GroupID";// 机构编码
    private final static String PARAM_GROUP_NAME = "GroupName";// 机构名称
    private final static String PARAM_PAYMENT = "Payment";// 支付方式（传“2”）
    private final static String PARAM_ORDER_REMARKS = "OrderRemarks";// 订单备注
    private final static String PARAM_IS_EMERGENCY = "OrderRemarks";// 是否紧急订单 [ 0 ：非紧急订单；1 紧急订单 ]

    private final static String PARAM_ORDER_ID = "orderID";// 是否紧急订单 [ 0 ：非紧急订单；1 紧急订单 ]

    /**
     * 新增第三方年检-主方法
     *
     * @param createDto
     * @return
     */
    @Override
    public ResponseResult<Boolean> addMOT(MotRequestCreateDto createDto) {
        logger.info("第三方年检 >>> 新增年检请求 >> {}", createDto);

        ResponseResult<Boolean> res = new ResponseResult<>();

        //拼接请求参数
        Map<String, Object> paramMap = buildParam(createDto);
        //发送年检请求给第三方
        String respResult = null;
        try {
            respResult = motUtils.doPost(addUrl, paramMap);
            logger.info("第三方年检 >> 申办结果 >> {}",respResult);
            MotRequestCreateDto thirdDto = JsonUtils.parse(respResult, MotRequestCreateDto.class);
            if (thirdDto.getResult() != 1) {
                return res.success(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return res.success(false);
        }
        //存储日志
        ThirdMotCreateDto beanDto = Convert.toThirdMotCreateDto(createDto, respResult);
        Integer resInt = motLogService.createMot(beanDto);
        if (resInt != null && resInt > 0) {
            return res.success(true);
        }
        return res.success(false);
    }


    /**
     * 新增第三方年检-拼接请求参数
     */
    private Map<String, Object> buildParam(MotRequestCreateDto createDto) {
        if (createDto == null) {
            return null;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(PARAM_KEY, strKey);
        paramMap.put(PARAM_GROUP_ID, strKey);
        paramMap.put(PARAM_GROUP_NAME, groupName);
        paramMap.put(PARAM_NAME, createDto.getOwnershipName());
        paramMap.put(PARAM_PHONE, createDto.getRecipientsPhone());
        paramMap.put(PARAM_ADDRESS, createDto.getMailAddress() + " " + "收件人:" + createDto.getRecipients());
        paramMap.put(PARAM_VIN, createDto.getVin());
        paramMap.put(PARAM_LICENSE, createDto.getLicencePlate());
        String insureProveUrl = createDto.getInsureProveUrl();
        if(!StringUtils.isEmpty(insureProveUrl)){
            if(insureProveUrl.indexOf(".pdf")>0){
                insureProveUrl = insureProveUrl.replaceAll(".pdf",".png");
            }
            paramMap.put(PARAM_INSURANCE, createDto.getInsureProveUrl());
        }
        paramMap.put(PARAM_IS_EMERGENCY, 0);
        paramMap.put(PARAM_PAYMENT, 2);
        return paramMap;
    }

    @Override
    public ResponseResult<List<ThirdMotStateDto>> getThirdMotState(List<Integer> carIds) {
        logger.info("第三方年检 >>> 查询年检状态 >> {}", carIds);

        ResponseResult res = new ResponseResult();
        List<ThirdMotStateDto> resultList = null;
        //根据carIds获取第三方订单集合
        List<ThirdMotDto> list = motLogService.getListByCarIds(carIds);

        Map<String, Integer> orderIdForCarIdMap = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        for (ThirdMotDto thirdMotDto : list) {
            if (thirdMotDto != null) {
                if (!StringUtils.isEmpty(thirdMotDto.getResultReason())
                        && thirdMotDto.getCarId() != null) {
                    sb.append(thirdMotDto.getResultReason() + ",");
                    orderIdForCarIdMap.put(thirdMotDto.getResultReason(), thirdMotDto.getCarId());
                }

            }

        }
        String orderIds = sb.toString().substring(0, sb.length() - 1);

        //组合参数，查询第三方接口订单状态
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(PARAM_ORDER_ID, orderIds);
        paramMap.put(PARAM_KEY, strKey);

        //请求第三方接口
        try {
            String resp = motUtils.doPost(queryUrl, paramMap);
            logger.info("第三方年检 >>> 调用第三方接口返回：{}",resp);
            resultList = parseJson(resp,orderIdForCarIdMap);
        } catch (Exception e) {
            e.printStackTrace();
            return res.error();
        }

        //年检状态入库
        if (resultList != null && resultList.size() > 0) {
            for (ThirdMotStateDto stateDto : resultList) {
                if (stateDto != null && stateDto.getOrderState() != 0 && stateDto.getOrderState() != 1) {
                    ThirdMotStateCreateDto creatDto = new ThirdMotStateCreateDto();
                    BeanUtils.copyProperties(stateDto, creatDto);
                    motLogStateService.createMotLogState(creatDto);

                }
            }
        }
        logger.info("第三方年检 >>> 车辆状态 >> 返回值："+resultList);
        return res.success(resultList);
    }

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("d946fc52-5572-46c5-a04b-3d5700c3c864",3024);
        map.put("a5bb946b-4ce3-486e-85fc-59419dffd616",3042);
        map.put("385e81c4-aef4-42a6-98a4-032295e66b73",5026);
        map.put("d483f376-cd13-4fb6-8a16-a1223788738b",25072);
        map.put("d483f376-cd13-4fb6-8a16-a1223788738b",25072);
        map.put("d483f376-cd13-4fb6-8a16-a1223788738b",25072);
        map.put("b7d443b7-748c-4137-aa77-e8b0baf1afbb",25044);
        map.put("b7d443b7-748c-4137-aa77-e8b0baf1afbb",25044);
        map.put("f991dbdb-a042-43fc-ba17-a50e62324f34",25043);
        String json="{\"result\":\"1\",\"reason\":[{\"OrderState\":\"1\",\"OrderID\":\"385e81c4-aef4-42a6-98a4-032295e66b73\",\"CancelReason\":\"测试1\"},{\"OrderState\":\"1\",\"OrderID\":\"d946fc52-5572-46c5-a04b-3d5700c3c864\",\"CancelReason\":\"测试数据\"},{\"OrderState\":\"4\",\"OrderID\":\"a5bb946b-4ce3-486e-85fc-59419dffd616\"},{\"OrderState\":\"4\",\"OrderID\":\"d483f376-cd13-4fb6-8a16-a1223788738b\"},{\"OrderState\":\"12\",\"OrderID\":\"f991dbdb-a042-43fc-ba17-a50e62324f34\",\"EMS_ComeNo\":\"5765632546\",\"BackPic\":\"http://www.jdcnj.com/图片1\"},{\"OrderID\":\"b7d443b7-748c-4137-aa77-e8b0baf1afbb\"}]}";
        parseJson(json,map);



    }

    private  static List<ThirdMotStateDto> parseJson(String jsonStr,Map<String, Integer> orderIdForCarIdMap){
        List<ThirdMotStateDto> resultList = null;
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Object result = jsonObject.get("result");
        if (result != null) {
            if ("1".equals(result)) {
                if (jsonObject.get("reason") != null) {
                    JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("reason").toString());
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            //返回值对象状态不能等于4（处理中）
                            if (obj != null) {
                                ThirdMotStateDto stateDto = getStateDto(obj, orderIdForCarIdMap);
                                if (stateDto != null) {
                                    if (resultList == null) {
                                        resultList = new ArrayList<>();
                                    }
                                    resultList.add(stateDto);
                                }
                            }
                        }
                    }
                }
            }else{
                logger.error("第三方年检 >>> 查询年检状态失败，错误码{}",result);
            }
        }
        return resultList;
    }

    private static ThirdMotStateDto getStateDto(JSONObject obj, Map<String, Integer> orderIdForCarIdMap) {
        ThirdMotStateDto stateDto = new ThirdMotStateDto();
        Object orderId = obj.get("OrderID");
        Object orderState = obj.get("OrderState");
        if (orderId != null) {
            stateDto.setCarId(orderIdForCarIdMap.get((String) orderId));
            stateDto.setOrderId((String) orderId);
            stateDto.setOrderState(0);
        } else {
            return null;
        }

        if (orderState != null) {//被回退状态
            if ("1".equals(orderState)) {
                stateDto.setOrderState(2);
                Object cancelReason = obj.get("CancelReason");
                if (obj.get("CancelReason") != null) {
                    stateDto.setCancelReason((String) cancelReason);
                }
            } else if ("12".equals(orderState)) {//办理完成的状态码
                stateDto.setOrderState(3);
                Object ems = obj.get("EMS_ComeNo");
                if (ems != null) {
                    stateDto.setEmsComeno((String) ems);
                }
                Object insureProveUrl = obj.get("BackPic");
                if (insureProveUrl != null) {
                    stateDto.setInsureProveUrl((String) insureProveUrl);
                }
            } else if ("4".equals(orderState) ) {
                stateDto.setOrderState(1);
            }
        }
        return stateDto;
    }


}
